#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

void *send_to_client(void *arg){
    int clientfd = *(int *)arg;
    char *send_buf=malloc(sizeof(char)*1024);
    memset(send_buf, 0, sizeof(send_buf));
    while(fgets(send_buf, sizeof(send_buf), stdin) != NULL){
        write(clientfd, send_buf, strlen(send_buf));
        memset(send_buf, 0, sizeof(send_buf));
    }
    //挥手，告知客户端
    printf("服务器关闭写\n");
    shutdown(clientfd, SHUT_WR);
    free(send_buf);

}

void *recv_from_client(void *arg){
    int clientfd = *(int *)arg;
    char *recv_buf=malloc(sizeof(char)*1024);
    memset(recv_buf, 0, sizeof(recv_buf));
    while(read(clientfd, recv_buf, sizeof(recv_buf)) > 0){
        write(STDOUT_FILENO, recv_buf, strlen(recv_buf));
        memset(recv_buf, 0, sizeof(recv_buf));
    }
    printf("客户端关闭读\n");
    shutdown(clientfd, SHUT_RD);
    free(recv_buf);
}

int main(int argc, char const *argv[])
{   
    //创建一个socket
    struct sockaddr_in addr, client_addr;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    //创建socket ，使用ipv4，使用tcp协议
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    //绑定地址和端口号
    bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

    //启动监听
    listen(sockfd, 128);
    
    //等待客户端连接,aspect,客户端的地址和端口号
    socklen_t client_addr_len = sizeof(client_addr);
    int clientfd=accept(sockfd, (struct sockaddr *)&client_addr,&client_addr_len);
    //打印客户端的ip和端口号
    printf("client ip:%s, port:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, send_to_client, &clientfd);
    pthread_create(&tid2, NULL, recv_from_client, &clientfd);

    //等待线程结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    //释放文件描述符
    close(clientfd);
    close(sockfd);


    return 0;
}
